package org.softmed.rest.generation.jar;

import groovy.lang.GroovyClassLoader;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import org.softmed.filehandling.FileUtil;

import com.google.inject.Inject;

public class DynamicJarLoader implements Runnable {

	List<String> jarFiles = new ArrayList<String>();

	String directory = "jars";
	String jarExtension = ".jar";

//	@Inject
//	static GroovyClassLoader groovyClassLoader;

	FileUtil util = new FileUtil();

	long miliSecondsToSleep = 3000;

	static Thread thread;

	public DynamicJarLoader() {

	}

	public void start() throws Throwable {
		if (thread != null)
			return;

		detectAndLoadNewJars();

		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		while (true) {
			try {
				detectAndLoadNewJars();
				Thread.sleep(miliSecondsToSleep);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	private void detectAndLoadNewJars() throws Throwable {

		File file = util.getFile(directory);
		if (file.exists() && !file.isDirectory())
			throw new RuntimeException("Directory " + directory
					+ " doesn't exist and name is taken !!!");

		if (!file.exists())
			file.mkdir();

		File[] files = file.listFiles();

		for (File child : files) {
			if (child.isFile() && child.getName().endsWith(jarExtension)) {
				if (jarFiles.contains(child.getName()))
					continue;

				jarFiles.add(child.getName());
				// groovyClassLoader.addURL(child.toURL());

				addJarToClassPath(child);

				System.out.println("Added " + child.getName());
			}
		}

	}

	private void addJarToClassPath(File child) throws Throwable {
		URL u = child.toURL();
		URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader
				.getSystemClassLoader();
		Class urlClass = URLClassLoader.class;
		Method method = urlClass.getDeclaredMethod("addURL",
				new Class[] { URL.class });
		method.setAccessible(true);
		method.invoke(urlClassLoader, new Object[] { u });
		System.out.println("Loading Jar: " + u);

	}

//	public static GroovyClassLoader getGroovyClassLoader() {
//		return groovyClassLoader;
//	}
//
//	public static void setGroovyClassLoader(GroovyClassLoader groovyClassLoader) {
//		DynamicJarLoader.groovyClassLoader = groovyClassLoader;
//	}

}
